// 1. 下载 vue-router 模块
//   yarn add vue-router
// 2. 按需导入模块
import Vue from "vue";
import VueRouter from "vue-router";
import { getToken } from "@/utils/localData.js";

// 3. 注册路由组件，可以用到 <router-view></router-view> 和 <router-link></router-link>
Vue.use(VueRouter);

// 4. 路由映射关系(路径与组件)
import Login from "@/views/Login.vue";
import Home from "@/views/Home.vue";
import Index from "@/views/Index.vue";
import List from "@/views/Post/List.vue";
import Publish from "@/views/Post/Publish.vue";

const routes = [
  { path: "/login", component: Login },
  { path: "/", redirect: "/home" },
  {
    path: "/home",
    component: Home,
    redirect: "/home/index",
    children: [
      { path: "index", component: Index },
      { path: "list", component: List },
      { path: "publish", component: Publish },
    ],
  },
];

// 5. 创建路由实例
const router = new VueRouter({
  routes: routes,
  mode: "history",
});

// .beforeEach()  前置导航守卫
//    to      要去哪里
//    from    来自哪里
//    next    是否方向的函数
router.beforeEach((to, from, next) => {
  // 后台管理系统，只有登录页是直接放行的
  if (to.path === "/login") {
    next();
  } else {
    // 其他的页面都要检查，有 token 放行，没有就去登录页
    if (getToken()) {
      next();
    } else {
      // next({ path: '/login' })
      next("/login");
    }
  }
});

// 6.1 导出路由实例
export default router;
